<template>
	<BasicModal v-bind="$attrs" @register="registerModal" width="65%" :title="getTitle" @ok="handleSubmit">
		<BasicForm @register="registerForm">
		</BasicForm>
	</BasicModal>
</template>
<script lang="ts">
	import { defineComponent, ref, computed, unref } from 'vue';
	import { BasicForm, useForm } from '/@/components/Form/index';
	import { formSchema } from './newsInfo.data';
	import { BasicModal, useModalInner } from '/@/components/Modal';
	import { newsInfoSave } from '/@/api/system/newsInfo';

	export default defineComponent({
		name: 'NewsInfoModal',
		components: { BasicModal, BasicForm },
		emits: ['success', 'register'],
		setup(_, { emit }) {
			const isUpdate = ref(true);

			const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
				labelWidth: 90,
				baseColProps: { span: 24 },
				schemas: formSchema,
				showActionButtonGroup: false,
			});

			const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
				resetFields();
				setModalProps({ confirmLoading: false });
				isUpdate.value = !!data?.isUpdate;

				if (unref(isUpdate)) {
					setFieldsValue({
						...data.record,
					});
				}
			});

			const getTitle = computed(() => (!unref(isUpdate) ? '新增配置' : '编辑配置'));

			async function handleSubmit() {
				try {
					const values = await validate();
					setModalProps({ confirmLoading: true });
					await newsInfoSave(values);
					closeModal();
					emit('success');
				} finally {
					setModalProps({ confirmLoading: false });
				}
			}

			return {
				registerModal,
				registerForm,
				getTitle,
				handleSubmit,
			};
		},
	});
</script>